package artid.com.arttogo.activity;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.integer;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.webkit.WebView.HitTestResult;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import artid.com.arttogo.R;
import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.bean.InfoOrder;
import artid.com.arttogo.bean.MoneyPay;
import artid.com.arttogo.bean.MoneyPayParser;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.AppUtil;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.pay.ALiPay_Utils;
import artid.com.arttogo.pay.AppRegister;
import artid.com.arttogo.pay.Constants;
import artid.com.arttogo.utils.MyBitmapImageViewTarget;
import artid.com.arttogo.utils.ToastUtil;

/**
 * TODO<请描述这个类是干什么的> 选择支付方式
 * 
 * @author 熊彬
 * @data: 2016-1-5 上午11:24:06
 * @version: V1.0
 */
public class ChoicePayActivity extends BaseActivity implements OnClickListener {
    //支付成功之后关闭
    public static Boolean isNeedClose = false;
    private LinearLayout mPerson_main_rela;
    private TextView mChoice_time;
    private TextView mChoice_code;
    private TextView mChoice_name;
    private TextView mChoice_cate;
    private TextView mChoice_size;
    private TextView mChoice_lefttime;
    private RelativeLayout mChoice_zfb;
    private ImageView mChoice_sel_imgzfb;
    private RelativeLayout mChoice_wx;
    private ImageView mChoice_wx_sel;
    private LinearLayout mChoice_pay_bottom;
    private TextView mChoice_cancel;
    private TextView mChoice_buy,time_tag;
    ImageView imgMain;
    private TimerTask task;
    private Timer timer;
    public static String id = "";
    TextView price;
    String payid = "2";
    int time;
    // 通知线程更改发送验证码按钮的值
    private Handler mHand = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 1){
                int time1 = (Integer) msg.obj;
                if (time1 > -1) {
                    String min = String.valueOf(time1/60);
                    String sec = String.valueOf(time1%60);
                    mChoice_lefttime.setText(min+"分"+sec+"秒");
                } else{
                    timer.cancel();
//                    AlertDialog alertDialog = new AlertDialog.Builder(ChoicePayActivity.this).setCancelable(false)
//                            .setTitle("提示").setMessage("此订单已失效，请重新购买")
//                            .setPositiveButton("好的", new DialogInterface.OnClickListener() {
//
//                                @Override
//                                public void onClick(DialogInterface arg0, int arg1) {
//                                    // TODO Auto-generated method stub
//                                    ArtToGoApp.getInstance().exitMall();
//                                    finish();
//                                }
//                            }).show();
                    time_tag.setText("该订单因支付超时已经关闭");
                    mChoice_time.setText("");
                    mChoice_buy.setBackgroundColor(Color.GRAY);
                    mChoice_buy.setText("支付超时");
                    mChoice_buy.setOnClickListener(new OnClickListener() {

                        @Override
                        public void onClick(View arg0) {
                            // TODO Auto-generated method stub
                            ArtToGoApp.getInstance().exitMall();
                            finish();
                        }
                    });
                }
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (isNeedClose){
            isNeedClose = false;
            finish();
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        id = getIntent().getExtras().getString("id");
        setContentView(R.layout.activity_choicepay);
        mContext = ChoicePayActivity.this;
        price = (TextView) findViewById(R.id.choice_price);
        mTittle = (TextView) findViewById(R.id.tittle_text);
        mTittle.setText("选择支付方式");
        mBack = (ImageView) findViewById(R.id.back_btn);
        mBack.setOnClickListener(this);
        time_tag = (TextView)findViewById(R.id.choice_time_tag);
        mPerson_main_rela = (LinearLayout) findViewById(R.id.person_main_rela);
        mChoice_time = (TextView) findViewById(R.id.choice_time);
        mChoice_code = (TextView) findViewById(R.id.choice_code);
        mChoice_name = (TextView) findViewById(R.id.choice_name);
        mChoice_cate = (TextView) findViewById(R.id.choice_cate);
        mChoice_size = (TextView) findViewById(R.id.choice_size);
        mChoice_lefttime = (TextView) findViewById(R.id.choice_lefttime);
        mChoice_zfb = (RelativeLayout) findViewById(R.id.choice_zfb);
        mChoice_zfb.setOnClickListener(this);

        mChoice_sel_imgzfb = (ImageView) findViewById(R.id.choice_sel_imgzfb);
        mChoice_wx = (RelativeLayout) findViewById(R.id.choice_wx);
        mChoice_wx.setOnClickListener(this);

        mChoice_wx_sel = (ImageView) findViewById(R.id.choice_wx_sel);
        mChoice_pay_bottom = (LinearLayout) findViewById(R.id.choice_pay_bottom);
        mChoice_cancel = (TextView) findViewById(R.id.choice_cancel);
        mChoice_cancel.setOnClickListener(this);
        mChoice_buy = (TextView) findViewById(R.id.choice_buy);
        mChoice_buy.setOnClickListener(this);
        imgMain = (ImageView) findViewById(R.id.choice_imgmain);
        reqData();
    }

    void reqData() {
        VolleyBasic.getInstance(ChoicePayActivity.this).post(Cache.infoOrder,
                VolleyMap.getInstance().infoOrder(id, "2"), InfoOrder.class,
                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        InfoOrder item = (InfoOrder) vd.getData();
                        mChoice_time.setText(item.getAdd_time());
                        mChoice_code.setText(item.getOrder_sn());
                        mChoice_name.setText(item.getGoods_name());
                        mChoice_cate.setText(item.getGc_name());
                        mChoice_size.setText(item.getGoods_size());


                        try {
                            time = 1800-item.getRestime();
                            taskTime();
                            timer.schedule(task, 0, 1000);
                        } catch (Exception e) {
                            // TODO: handle exception
                        }


                        price.setText(item.getGoods_price());
                        Glide.with(ChoicePayActivity.this).load(item.getGoods_image()+ AppUtil.picWidthSmallUrl)
                                .asBitmap().centerCrop()
                                .placeholder(R.drawable.ic_menu_rotate).error(R.drawable.ic_menu_rotate)
                                .into(new MyBitmapImageViewTarget(imgMain));

                        return;
                        // }
                        // ArtistInfo list = (ArtistInfo)vd.getData();
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }
    public void taskTime() {

        timer = new Timer();
        task = new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                Message message = mHand.obtainMessage(1, time--);
                // message.arg1=time--;
                mHand.sendMessage(message);
            }
        };
    }
    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        switch (arg0.getId()) {
            case R.id.back_btn:
                ArtToGoApp.getInstance().exitMall();
                finish();
                break;
            case R.id.choice_zfb:
                mChoice_sel_imgzfb.setVisibility(View.VISIBLE);

                mChoice_wx_sel.setVisibility(View.INVISIBLE);

                payid = "2";
                break;
            case R.id.choice_wx:
                mChoice_sel_imgzfb.setVisibility(View.INVISIBLE);

                mChoice_wx_sel.setVisibility(View.VISIBLE);

                payid = "6";
                break;
            case R.id.choice_cancel:

                AlertDialog alertDialog = new AlertDialog.Builder(mContext).setMessage("喜欢的作品，怎可轻易留给Ta人")
                        .setPositiveButton("我再想想", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                // TODO Auto-generated method stub

                            }
                        }).setNegativeButton("去意已决", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                // TODO Auto-generated method stub
                                ArtToGoApp.getInstance().exitMall();
                                finish();
                            }
                        }).show();
                break;
            case R.id.choice_buy:
//			reqPay(id,price.getText().toString(),payid);
                reqMoney();
                break;

            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        ArtToGoApp.getInstance().exitMall();
        finish();
    }
    void reqMoney() {
        VolleyBasic.getInstance(ChoicePayActivity.this).post(Cache.moneyPay,
                VolleyMap.getInstance().moneyPay(id,price.getText().toString(), payid), MoneyPay.class,
                new VolleyCallback() {

                    @Override
                    public void onSuccess(VolleyData vd) {
                        // TODO Auto-generated method stub
                        final MoneyPay item = (MoneyPay)vd.getData();
                        if (item.getState()==0) {
                            ToastUtil.toast(ChoicePayActivity.this, "订单异常");
                            return;
                        }
                        if (payid.equals("2")) {
                            //支付宝支付
                               ALiPay_Utils.getInstance().ALiPay(ChoicePayActivity.this,item.getPay_sn(), mChoice_name.getText().toString(), "艺术品",price.getText().toString(), item.getUrl(), new ALiPay_Utils.PayListener() {
                                   @Override
                                   public void onSuccess() {
                                      ToastUtil.toast(mContext,"支付成功！");
                                       ArtToGoApp.getInstance().addMallActivity(ChoicePayActivity.this);
                                       Intent intent = new Intent(ChoicePayActivity.this,PaySuccessActivity.class);
                                       intent.putExtra("id", id);
                                       startActivity(intent);
                                       finish();
                                   }

                                   @Override
                                   public void onFailed() {
                                       ToastUtil.toast(mContext,"支付失败");
                                   }

                                   @Override
                                   public void onInConfirmation() {
                                       ToastUtil.toast(mContext,"支付结果确认中");
                                   }
                               });
                        }else if (payid.equals("6")) {
                            if(item.getState()==1){
                                //微信支付
//                               //在这之前先给微信参数设置值
                               Constants.APP_ID = item.getAppid();
//                               //商户号，在商户平台设置
                               Constants.MCH_ID = item.getPartnerid();
//                               //  API密钥，在商户平台设置
                               Constants.API_KEY = "YqZAi2e8C9F9z2XBiFHSePNeZ6UDgfI4";
                               IWXAPI msgApi = WXAPIFactory.createWXAPI(mContext, null);
                               msgApi.registerApp(Constants.APP_ID);
                               PayReq mPayReq = new PayReq();
                               mPayReq.appId = item.getAppid();
                               mPayReq.partnerId = item.getPartnerid();// 商户号
                               mPayReq.prepayId = item.getPrepayid(); // 预支付交易会话ID
                               mPayReq.packageValue = item.getPackages();// 扩展字段
                               mPayReq.nonceStr = item.getNoncestr(); // 随机字符串
                               mPayReq.timeStamp = item.getTimestamp(); // 时间戳
                               mPayReq.sign = item.getSign();// 签名
                               msgApi.sendReq(mPayReq);
                            }
                        }

                        return;
                        // }
                        // ArtistInfo list = (ArtistInfo)vd.getData();
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub

                    }
                });
    }

    /**
     提交支付（测试）
     口令	token
     订单编码	order_id
     下单金额	orderamount
     支付方式名称代码	payment_id	2支付宝，6微信
     类型	 type	商城支付的时候传
     商品名字	goods_name	商城支付时候传
     */
//   private void postPay(final String payment_id) {
//       VolleyBasic.getInstance(ChoicePayActivity.this).post(Cache.moneyPay,
//               VolleyMap.getInstance().moneyPay("409","1",payment_id,"","测试商品名"),
//               MoneyPayParser.class, new VolleyCallback() {
//                   @Override
//                   public void onSuccess(VolleyData vd) {
//                       // TODO Auto-generated method stub
//                       MoneyPayParser bean= (MoneyPayParser) vd.getData();
//                       if(bean.getState()==1){
//                           if("2".equals(payment_id)){
//                               //支付宝支付
//                               ALiPay_Utils.getInstance().ALiPay(ChoicePayActivity.this, "测试商品名称", "测试商品描述", "0.01", bean.getUrl(), new ALiPay_Utils.PayListener() {
//                                   @Override
//                                   public void onSuccess() {
//                                       ToastUtil.toast(mContext,"支付成功");
//                                   }
//
//                                   @Override
//                                   public void onFailed() {
//                                       ToastUtil.toast(mContext,"支付失败");
//                                   }
//
//                                   @Override
//                                   public void onInConfirmation() {
//                                       ToastUtil.toast(mContext,"支付结果确认中");
//                                   }
//                               });
//                           }else if("6".equals(payment_id)) {
//                               //微信支付
//                               //在这之前先给微信参数设置值
//                               Constants.APP_ID = bean.getAppid();
//                               //商户号，在商户平台设置
//                               Constants.MCH_ID = bean.getPartnerid();
//                               //  API密钥，在商户平台设置
//                               Constants.API_KEY = "YqZAi2e8C9F9z2XBiFHSePNeZ6UDgfI4";
//                               IWXAPI msgApi = WXAPIFactory.createWXAPI(mContext, null);
//                               msgApi.registerApp(Constants.APP_ID);
//                               PayReq mPayReq = new PayReq();
//                               mPayReq.appId = bean.getAppid();
//                               mPayReq.partnerId = bean.getPartnerid();// 商户号
//                               mPayReq.prepayId = bean.getPrepayid(); // 预支付交易会话ID
//                               mPayReq.packageValue = bean.getPackages();// 扩展字段
//                               mPayReq.nonceStr = bean.getNoncestr(); // 随机字符串
//                               mPayReq.timeStamp = bean.getTimestamp(); // 时间戳
//                               mPayReq.sign = bean.getSign();// 签名
//                               msgApi.sendReq(mPayReq);
//                           }
//                       }else{
//                           ToastUtil.toast(mContext,"获取支付信息失败!!");
//                       }
//                   }
//
//                   @Override
//                   public void onError(VolleyError volleyError) {
//                       // TODO Auto-generated method stub
//
//                   }
//               });
//   }
}
